﻿require([
    "jquery",
    "jquery-migrate",
    "jquery-ui",
    "bootstrap",
    "bootstrap-hover-dropdown",
    "jquery-slimscroll",
    "jquery-blockui",
    "jquery-cokie",
    "jquery-uniform",
    "bootstrap-switch",
    "jquery-gritter",
    "jquery-backstretch",
    "jquery-uploadify",
    "signalr",
    "ko",
    "akcy"
], function ($) {
    var v = window.location.toString().getUrlParm("v");
    if (v == "" || v == undefined) {
        window.location = "/";
    }

    var akcy = arguments[arguments.length - 1];
    var ko = arguments[arguments.length - 2];
    var main = function () {

        var handleSession = function () {
            var sessionid = akcy.session.get();
            if (sessionid != undefined && sessionid != "") {
                akcy.ajaxpostsilent("/ak56api/home/checklogin?sessionid=" + sessionid).done(function (rst) {
                    if (rst == undefined || !rst.status) {
                        window.location = "/";
                    }

                    $("body").data("currentuser", {
                        username: rst.name,
                        node: rst.node,
                        branche: rst.branche,
                        nodeName: rst.nodeName,
                        brancheName: rst.brancheName
                    });
                    akcy.currentuser.set(rst.name);
                    $(".username").html(rst.name);

                }).fail(function () {
                    window.location = "/";
                });
            } else {
                window.location = "/";
            }
        };

        var handleTheme = function () {

            var panel = $('.theme-panel');

            panel.draggable();

            if ($('body').hasClass('page-boxed') === false) {
                $('.layout-option', panel).val("fluid");
            }

            $('.sidebar-option', panel).val("default");
            $('.page-header-option', panel).val("fixed");
            $('.page-footer-option', panel).val("fixed");
            if ($('.sidebar-pos-option').attr("disabled") === false) {
                $('.sidebar-pos-option', panel).val(akcy.ui.isRTL() ? 'right' : 'left');
            }

            //handle theme layout
            var resetLayout = function () {
                $("body").
                removeClass("page-boxed").
                removeClass("page-footer-fixed").
                removeClass("page-sidebar-fixed").
                removeClass("page-header-fixed").
                removeClass("page-sidebar-reversed");

                $('.page-header > .page-header-inner').removeClass("container");

                if ($('.page-container').parent(".container").size() === 1) {
                    $('.page-container').insertAfter('body > .clearfix');
                }

                if ($('.page-footer > .container').size() === 1) {
                    $('.page-footer').html($('.page-footer > .container').html());
                } else if ($('.page-footer').parent(".container").size() === 1) {
                    $('.page-footer').insertAfter('.page-container');
                    $('.scroll-to-top').insertAfter('.page-footer');
                }

                $(".top-menu > .navbar-nav > li.dropdown").removeClass("dropdown-dark");

                $('body > .container').remove();
            };

            var lastSelectedLayout = '';

            var setLayout = function () {

                var layoutOption = $('.layout-option', panel).val();
                var sidebarOption = $('.sidebar-option', panel).val();
                var headerOption = $('.page-header-option', panel).val();
                var footerOption = $('.page-footer-option', panel).val();
                var sidebarPosOption = $('.sidebar-pos-option', panel).val();
                var sidebarStyleOption = $('.sidebar-style-option', panel).val();
                var sidebarMenuOption = $('.sidebar-menu-option', panel).val();
                var headerTopDropdownStyle = $('.page-header-top-dropdown-style-option', panel).val();

                if (sidebarOption == "fixed" && headerOption == "default") {
                    alert('Default Header with Fixed Sidebar option is not supported. Proceed with Fixed Header with Fixed Sidebar.');
                    $('.page-header-option', panel).val("fixed");
                    $('.sidebar-option', panel).val("fixed");
                    sidebarOption = 'fixed';
                    headerOption = 'fixed';
                }

                resetLayout(); // reset layout to default state

                if (layoutOption === "boxed") {
                    $("body").addClass("page-boxed");

                    // set header
                    $('.page-header > .page-header-inner').addClass("container");
                    var cont = $('body > .clearfix').after('<div class="container"></div>');

                    // set content
                    $('.page-container').appendTo('body > .container');

                    // set footer
                    if (footerOption === 'fixed') {
                        $('.page-footer').html('<div class="container">' + $('.page-footer').html() + '</div>');
                    } else {
                        $('.page-footer').appendTo('body > .container');
                    }
                }

                if (lastSelectedLayout != layoutOption) {
                    //layout changed, run responsive handler: 
                    akcy.ui.runResizeHandlers();
                }
                lastSelectedLayout = layoutOption;

                //header
                if (headerOption === 'fixed') {
                    $("body").addClass("page-header-fixed");
                    $(".page-header").removeClass("navbar-static-top").addClass("navbar-fixed-top");
                } else {
                    $("body").removeClass("page-header-fixed");
                    $(".page-header").removeClass("navbar-fixed-top").addClass("navbar-static-top");
                }

                //sidebar
                if ($('body').hasClass('page-full-width') === false) {
                    if (sidebarOption === 'fixed') {
                        $("body").addClass("page-sidebar-fixed");
                        $("page-sidebar-menu").addClass("page-sidebar-menu-fixed");
                        $("page-sidebar-menu").removeClass("page-sidebar-menu-default");
                        handleLayout.initFixedSidebarHoverEffect();
                    } else {
                        $("body").removeClass("page-sidebar-fixed");
                        $("page-sidebar-menu").addClass("page-sidebar-menu-default");
                        $("page-sidebar-menu").removeClass("page-sidebar-menu-fixed");
                        $('.page-sidebar-menu').unbind('mouseenter').unbind('mouseleave');
                    }
                }

                // top dropdown style
                if (headerTopDropdownStyle === 'dark') {
                    $(".page-header-inner .hor-menu").removeClass("hor-menu-light");
                } else {
                    $(".page-header-inner .hor-menu").addClass("hor-menu-light");
                }

                //footer 
                if (footerOption === 'fixed') {
                    $("body").addClass("page-footer-fixed");
                } else {
                    $("body").removeClass("page-footer-fixed");
                }

                //sidebar style
                if (sidebarStyleOption === 'light') {
                    $(".page-sidebar-menu").addClass("page-sidebar-menu-light");
                } else {
                    $(".page-sidebar-menu").removeClass("page-sidebar-menu-light");
                }

                //sidebar menu 
                if (sidebarMenuOption === 'hover') {
                    if (sidebarOption == 'fixed') {
                        $('.sidebar-menu-option', panel).val("accordion");
                        alert("Hover Sidebar Menu is not compatible with Fixed Sidebar Mode. Select Default Sidebar Mode Instead.");
                    } else {
                        $(".page-sidebar-menu").addClass("page-sidebar-menu-hover-submenu");
                    }
                } else {
                    $(".page-sidebar-menu").removeClass("page-sidebar-menu-hover-submenu");
                }

                //sidebar position
                if (akcy.ui.isRTL()) {
                    if (sidebarPosOption === 'left') {
                        $("body").addClass("page-sidebar-reversed");
                        $('#frontend-link').tooltip('destroy').tooltip({
                            placement: 'right'
                        });
                    } else {
                        $("body").removeClass("page-sidebar-reversed");
                        $('#frontend-link').tooltip('destroy').tooltip({
                            placement: 'left'
                        });
                    }
                } else {
                    if (sidebarPosOption === 'right') {
                        $("body").addClass("page-sidebar-reversed");
                        $('#frontend-link').tooltip('destroy').tooltip({
                            placement: 'left'
                        });
                    } else {
                        $("body").removeClass("page-sidebar-reversed");
                        $('#frontend-link').tooltip('destroy').tooltip({
                            placement: 'right'
                        });
                    }
                }
                handleLayout.fixContentHeight(); // fix content height            
                handleLayout.initFixedSidebar(); // reinitialize fixed sidebar
            };

            // handle theme colors
            var setColor = function (color) {
                var color_ = (akcy.ui.isRTL() ? color + '-rtl' : color);
                $('#themes_color').attr("href", handleLayout.getLayoutCssPath() + 'themes/' + color_ + ".css");
                //if (color == 'light2') {
                //    $('.page-logo img').attr('src', handleLayout.getLayoutImgPath() + 'logo.png');
                //} else {
                //    $('.page-logo img').attr('src', handleLayout.getLayoutImgPath() + 'logo.png');
                //}
            };

            $('.toggler', panel).click(function () {
                $('.toggler').hide();
                $('.toggler-close').show();
                $('.theme-panel > .theme-options').show();
            });

            $('.toggler-close', panel).click(function () {
                $('.toggler').show();
                $('.toggler-close').hide();
                $('.theme-panel > .theme-options').hide();
            });

            $('.theme-colors > ul > li', panel).click(function () {
                var color = $(this).attr("data-style");
                setColor(color);
                $('ul > li', panel).removeClass("current");
                $(this).addClass("current");
            });

            // set default theme options:

            if ($("body").hasClass("page-boxed")) {
                $('.layout-option', panel).val("boxed");
            }

            if ($("body").hasClass("page-sidebar-fixed")) {
                $('.sidebar-option', panel).val("fixed");
            }

            if ($("body").hasClass("page-header-fixed")) {
                $('.page-header-option', panel).val("fixed");
            }

            if ($("body").hasClass("page-footer-fixed")) {
                $('.page-footer-option', panel).val("fixed");
            }

            if ($("body").hasClass("page-sidebar-reversed")) {
                $('.sidebar-pos-option', panel).val("right");
            }

            if ($(".page-sidebar-menu").hasClass("page-sidebar-menu-light")) {
                $('.sidebar-style-option', panel).val("light");
            }

            if ($(".page-sidebar-menu").hasClass("page-sidebar-menu-hover-submenu")) {
                $('.sidebar-menu-option', panel).val("hover");
            }

            var sidebarOption = $('.sidebar-option', panel).val();
            var headerOption = $('.page-header-option', panel).val();
            var footerOption = $('.page-footer-option', panel).val();
            var sidebarPosOption = $('.sidebar-pos-option', panel).val();
            var sidebarStyleOption = $('.sidebar-style-option', panel).val();
            var sidebarMenuOption = $('.sidebar-menu-option', panel).val();

            $('.layout-option, .page-header-option, .page-header-top-dropdown-style-option, .sidebar-option, .page-footer-option, .sidebar-pos-option, .sidebar-style-option, .sidebar-menu-option', panel).change(setLayout);
        };

        var setThemeStyle = function (style) {
            var file = (style === 'rounded' ? 'components-rounded' : 'components');
            file = (akcy.ui.isRTL() ? file + '-rtl' : file);

            $('#style_components').attr("href", akcy.ui.getGlobalCssPath() + file + ".css");

            if ($.cookie) {
                $.cookie('layout-style-option', style);
            }
        };

        var handleLayout = function () {

            var resBreakpointMd = akcy.ui.getResponsiveBreakpoint('md');

            //* BEGIN:CORE HANDLERS *//
            // this function handles responsive layout on screen size resize or mobile device rotate.

            // Set proper height for sidebar and content. The content and sidebar height must be synced always.
            var handleSidebarAndContentHeight = function () {
                var content = $('.page-content');
                var sidebar = $('.page-sidebar');
                var body = $('body');
                var height;

                if (body.hasClass("page-footer-fixed") === true && body.hasClass("page-sidebar-fixed") === false) {
                    var available_height = akcy.ui.getViewPort().height - $('.page-footer').outerHeight() - $('.page-header').outerHeight();
                    if (content.height() < available_height) {
                        content.attr('style', 'min-height:' + available_height + 'px');
                    }
                } else {
                    if (body.hasClass('page-sidebar-fixed')) {
                        height = _calculateFixedSidebarViewportHeight();
                        if (body.hasClass('page-footer-fixed') === false) {
                            height = height - $('.page-footer').outerHeight();
                        }
                    } else {
                        var headerHeight = $('.page-header').outerHeight();
                        var footerHeight = $('.page-footer').outerHeight();

                        if (akcy.ui.getViewPort().width < resBreakpointMd) {
                            height = akcy.ui.getViewPort().height - headerHeight - footerHeight;
                        } else {
                            height = sidebar.height() + 20;
                        }

                        if ((height + headerHeight + footerHeight) <= akcy.ui.getViewPort().height) {
                            height = akcy.ui.getViewPort().height - headerHeight - footerHeight;
                        }
                    }
                    content.attr('style', 'min-height:' + height + 'px');
                }
            };

            // Handle sidebar menu links
            var handleSidebarMenuActiveLink = function (mode, el) {
                var url = location.hash.toLowerCase();

                var menu = $('.page-sidebar-menu');

                if (mode === 'click' || mode === 'set') {
                    el = $(el);
                } else if (mode === 'match') {
                    menu.find("li > a").each(function () {
                        var path = $(this).attr("href").toLowerCase();
                        // url match condition         
                        if (path.length > 1 && url.substr(1, path.length - 1) == path.substr(1)) {
                            el = $(this);
                            return;
                        }
                    });
                }

                if (!el || el.size() == 0) {
                    return;
                }

                if (el.attr('href').toLowerCase() === 'javascript:;' || el.attr('href').toLowerCase() === '#') {
                    return;
                }

                var slideSpeed = parseInt(menu.data("slide-speed"));
                var keepExpand = menu.data("keep-expanded");

                // disable active states
                menu.find('li.active').removeClass('active');
                menu.find('li > a > .selected').remove();

                if (menu.hasClass('page-sidebar-menu-hover-submenu') === false) {
                    menu.find('li.open').each(function () {
                        if ($(this).children('.sub-menu').size() === 0) {
                            $(this).removeClass('open');
                            $(this).find('> a > .arrow.open').removeClass('open');
                        }
                    });
                } else {
                    menu.find('li.open').removeClass('open');
                }

                el.parents('li').each(function () {
                    $(this).addClass('active');
                    $(this).find('> a > span.arrow').addClass('open');

                    if ($(this).parent('ul.page-sidebar-menu').size() === 1) {
                        $(this).find('> a').append('<span class="selected"></span>');
                    }

                    if ($(this).children('ul.sub-menu').size() === 1) {
                        $(this).addClass('open');
                    }
                });

                if (mode === 'click') {
                    if (akcy.ui.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page 
                        $('.page-header .responsive-toggler').click();
                    }
                }
            };

            // Handle sidebar menu
            var handleSidebarMenu = function () {

                //load data for menu
                akcy.ajaxpost("/ak56api/home/menu?sessionID=" + akcy.session.get()).done(function (rst) {

                    //保存页面权限
                    $("body").data("pagerights", rst);

                    //加载初始页
                    akcy.openwindow("控制台", "p_dashboard", true, "/application/home/dashboard.html");

                    var buildData = function () {
                        var getChild = function (parentID) {
                            var childs = [];
                            for (var i = 0; i < rst.length; i++) {
                                if (rst[i].P_ParentID == parentID && rst[i].P_FromMenu == 1) {
                                    childs.push(rst[i]);
                                }
                            }
                            return childs;
                        }

                        var getData = function (nodes) {
                            for (var i = 0; i < nodes.length; i++) {
                                nodes[i]["P_Childs"] = getChild(nodes[i].P_ID);
                                getData(nodes[i]["P_Childs"]);
                            }
                        }

                        var data = getChild(0);

                        getData(data);

                        return data;
                    }

                    var buildMenu = function (data) {
                        var getNodeHtml = function (node) {
                            //打开class open
                            //选中class active
                            var nodeTplt = "<li class='" + (node.P_ID == 1 ? "active" : "") + "'>";
                            nodeTplt += "<a href='" + node.P_Url + "' pageid='" + node.P_Code + "'>";
                            nodeTplt += "<i class='" + (node.P_Icon != undefined && node.P_Icon != "" ? node.P_Icon : "icon-folder") + "'></i>";
                            nodeTplt += "<span class='" + (node.P_ParentID == 0 ? "title" : "") + "'>" + node.P_MenuName + "</span>";
                            nodeTplt += (node.P_Childs != undefined && node.P_Childs.length > 0 ? "<span class='arrow'></span>" : "");
                            nodeTplt += "</a>";
                            nodeTplt += (node.P_Childs != undefined && node.P_Childs.length > 0 ? "<ul class='sub-menu'></ul>" : "");
                            nodeTplt += "</li>";

                            return $(nodeTplt);
                        };

                        var buildDataNodes = function (data, $Elm) {
                            if (data != undefined) {
                                for (var i = 0; i < data.length; i++) {
                                    var $nodeHtml = getNodeHtml(data[i]);
                                    if (data[i].P_Childs != undefined && data[i].P_Childs.length > 0) {
                                        buildDataNodes(data[i].P_Childs, $nodeHtml.find("ul.sub-menu"));
                                    }
                                    $Elm.append($nodeHtml);
                                }
                            }
                        };

                        var data = buildData();

                        buildDataNodes(data, $(".page-sidebar-menu"));
                    };

                    buildMenu();
                });

                // handle sidebar link click
                $('.page-sidebar').on('click', 'li > a', function (e) {
                    var hasSubMenu = $(this).next().hasClass('sub-menu');

                    if (akcy.ui.getViewPort().width >= resBreakpointMd && $(this).parents('.page-sidebar-menu-hover-submenu').size() === 1) { // exit of hover sidebar menu
                        return;
                    }

                    if (hasSubMenu === false) {
                        if (akcy.ui.getViewPort().width < resBreakpointMd && $('.page-sidebar').hasClass("in")) { // close the menu on mobile view while laoding a page 
                            $('.page-header .responsive-toggler').click();
                        }

                        var src = $(this).attr("href");
                        if (src != "#" && src != "javascript:;") {
                            var title = $(this).find("span").html();
                            var pageid = $(this).attr("pageid");

                            akcy.openwindow(title, pageid, true, src);
                        }

                        handleSidebarMenuActiveLink("set", $(this));

                        return false;
                    }

                    if ($(this).next().hasClass('sub-menu always-open')) {
                        return;
                    }

                    var parent = $(this).parent().parent();
                    var the = $(this);
                    var menu = $('.page-sidebar-menu');
                    var sub = $(this).next();

                    var autoScroll = menu.data("auto-scroll");
                    var slideSpeed = parseInt(menu.data("slide-speed"));
                    var keepExpand = menu.data("keep-expanded");

                    if (keepExpand !== true) {
                        parent.children('li.open').children('a').children('.arrow').removeClass('open');
                        parent.children('li.open').children('.sub-menu:not(.always-open)').slideUp(slideSpeed);
                        parent.children('li.open').removeClass('open');
                    }

                    var slideOffeset = -200;

                    if (sub.is(":visible")) {
                        $('.arrow', $(this)).removeClass("open");
                        $(this).parent().removeClass("open");
                        sub.slideUp(slideSpeed, function () {
                            if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
                                if ($('body').hasClass('page-sidebar-fixed')) {
                                    menu.slimScroll({
                                        'scrollTo': (the.position()).top
                                    });
                                } else {
                                    akcy.ui.scrollTo(the, slideOffeset);
                                }
                            }
                            handleSidebarAndContentHeight();
                        });
                    } else if (hasSubMenu) {
                        $('.arrow', $(this)).addClass("open");
                        $(this).parent().addClass("open");
                        sub.slideDown(slideSpeed, function () {
                            if (autoScroll === true && $('body').hasClass('page-sidebar-closed') === false) {
                                if ($('body').hasClass('page-sidebar-fixed')) {
                                    menu.slimScroll({
                                        'scrollTo': (the.position()).top
                                    });
                                } else {
                                    akcy.ui.scrollTo(the, slideOffeset);
                                }
                            }
                            handleSidebarAndContentHeight();
                        });
                    }

                    handleSidebarMenuActiveLink("set", $(this));

                    e.preventDefault();
                });

                // top nemu click 
                $('.mega-menu-content').on('click', 'a', function () {
                    handleSidebarMenuActiveLink("set", $(".page-sidebar-menu a[pageid='" + $(this).attr('pageid') + "']"));
                    akcy.openwindow($(this).html(), $(this).attr('pageid'), false);
                });

                // handle scrolling to top on responsive menu toggler click when header is fixed for mobile view
                $(document).on('click', '.page-header-fixed-mobile .page-header .responsive-toggler', function () {
                    akcy.ui.scrollTop();
                });

                // handle sidebar hover effect        
                handleFixedSidebarHoverEffect();

                // handle the search bar close
                $('.page-sidebar').on('click', '.sidebar-search .remove', function (e) {
                    e.preventDefault();
                    $('.sidebar-search').removeClass("open");
                });

                // handle the search query submit on enter press
                //$('.page-sidebar .sidebar-search').on('keypress', 'input.form-control', function (e) {
                //    if (e.which == 13) {
                //        $('.sidebar-search').submit();
                //        return false; //<---- Add this line
                //    }
                //});

                // handle the search submit(for sidebar search and responsive mode of the header search)
                $('.sidebar-search .submit').on('click', function (e) {

                    e.preventDefault();
                });

                // handle close on body click
                if ($('.sidebar-search').size() !== 0) {
                    $('.sidebar-search .input-group').on('click', function (e) {
                        e.stopPropagation();
                    });

                    $('body').on('click', function () {
                        if ($('.sidebar-search').hasClass('open')) {
                            $('.sidebar-search').removeClass("open");
                        }
                    });
                }
            };

            // Helper function to calculate sidebar height for fixed sidebar layout.
            var _calculateFixedSidebarViewportHeight = function () {
                var sidebarHeight = akcy.ui.getViewPort().height - $('.page-header').outerHeight();
                if ($('body').hasClass("page-footer-fixed")) {
                    sidebarHeight = sidebarHeight - $('.page-footer').outerHeight();
                }

                return sidebarHeight;
            };

            // Handles fixed sidebar
            var handleFixedSidebar = function () {
                var menu = $('.page-sidebar-menu');

                akcy.ui.destroySlimScroll(menu);

                if ($('.page-sidebar-fixed').size() === 0) {
                    handleSidebarAndContentHeight();
                    return;
                }

                if (akcy.ui.getViewPort().width >= resBreakpointMd) {
                    menu.attr("data-height", _calculateFixedSidebarViewportHeight());
                    akcy.ui.initSlimScroll(menu);
                    handleSidebarAndContentHeight();
                }
            };

            // Handles sidebar toggler to close/hide the sidebar.
            var handleFixedSidebarHoverEffect = function () {
                var body = $('body');
                if (body.hasClass('page-sidebar-fixed')) {
                    $('.page-sidebar').on('mouseenter', function () {
                        if (body.hasClass('page-sidebar-closed')) {
                            $(this).find('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
                        }
                    }).on('mouseleave', function () {
                        if (body.hasClass('page-sidebar-closed')) {
                            $(this).find('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
                        }
                    });
                }
            };

            // Hanles sidebar toggler
            var handleSidebarToggler = function () {
                var body = $('body');
                if ($.cookie && $.cookie('sidebar_closed') === '0' && akcy.ui.getViewPort().width >= resBreakpointMd) {
                    $('body').removeClass('page-sidebar-closed');
                    $('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
                }

                // handle sidebar show/hide
                $('body').on('click', '.sidebar-toggler', function (e) {
                    var sidebar = $('.page-sidebar');
                    var sidebarMenu = $('.page-sidebar-menu');
                    $(".sidebar-search", sidebar).removeClass("open");

                    if (body.hasClass("page-sidebar-closed")) {
                        body.removeClass("page-sidebar-closed");
                        sidebarMenu.removeClass("page-sidebar-menu-closed");
                        if ($.cookie) {
                            $.cookie('sidebar_closed', '0');
                        }
                    } else {
                        body.addClass("page-sidebar-closed");
                        sidebarMenu.addClass("page-sidebar-menu-closed");
                        if (body.hasClass("page-sidebar-fixed")) {
                            sidebarMenu.trigger("mouseleave");
                        }
                        if ($.cookie) {
                            $.cookie('sidebar_closed', '1');
                        }
                    }

                    $(window).trigger('resize');
                });
            };

            // Handles the horizontal menu
            var handleHorizontalMenu = function () {
                //handle tab click
                $('.page-header').on('click', '.hor-menu a[data-toggle="tab"]', function (e) {
                    e.preventDefault();
                    var nav = $(".hor-menu .nav");
                    var active_link = nav.find('li.current');
                    $('li.active', active_link).removeClass("active");
                    $('.selected', active_link).remove();
                    var new_link = $(this).parents('li').last();
                    new_link.addClass("current");
                    new_link.find("a:first").append('<span class="selected"></span>');
                });

                // handle search box expand/collapse        
                $('.page-header').on('click', '.search-form', function (e) {
                    $(this).addClass("open");
                    $(this).find('.form-control').focus();

                    $('.page-header .search-form .form-control').on('blur', function (e) {
                        $(this).closest('.search-form').removeClass("open");
                        $(this).unbind("blur");
                    });
                });

                // handle hor menu search form on enter press
                $('.page-header').on('keypress', '.hor-menu .search-form .form-control', function (e) {
                    if (e.which == 13) {
                        $(this).closest('.search-form').submit();
                        return false;
                    }
                });

                // handle header search button click
                $('.page-header').on('mousedown', '.search-form.open .submit', function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).closest('.search-form').submit();
                });

                // handle hover dropdown menu for desktop devices only
                $('[data-hover="megamenu-dropdown"]').not('.hover-initialized').each(function () {
                    $(this).dropdownHover();
                    $(this).addClass('hover-initialized');
                });

                // handle logout
                $("#logout").click(function () {
                    akcy.confirm("确定注销此帐号吗？", function () {
                        var sessionid = akcy.session.get();
                        akcy.ajaxpostsilent("/ak56api/home/logout?sessionid=" + sessionid).always(function () {
                            akcy.session.set("").done(function () {
                                window.location = "/";
                            });
                        });
                    });
                });

                // handle lock screen
                $("#lock").click(function () {
                    var sessionid = akcy.session.get();
                    akcy.ajaxpostsilent("/ak56api/home/logout?sessionid=" + sessionid).always(function () {
                        akcy.session.set("").done(function () {
                            $(".page-lock").fadeIn();
                            $(".backstretch").fadeIn();
                        });
                    });
                });

                $("#lock-btn").click(function () {
                    $("#lock-alert span").html("解锁中，请稍等...");
                    $("#lock-alert").removeClass("alert-danger").addClass("alert-success").slideDown(function () {

                        var password = $("#lock-password").val();

                        if (password == "" || password == undefined) {
                            $("#lock-alert span").html("请输入密码！");
                            $("#lock-alert").removeClass("alert-success").addClass("alert-danger").slideDown();
                            return;
                        }

                        var username = akcy.currentuser.get();

                        akcy.ajaxpostsilent("/ak56api/home/login?username=" + username + "&password=" + password).done(function (rst) {
                            $.when(akcy.session.set(rst), akcy.currentuser.set(username)).done(function () {
                                setTimeout(function () {
                                    $("#lock-password").val("");
                                    $("#lock-alert").hide();
                                    $(".page-lock").fadeOut();
                                    $(".backstretch").fadeOut();
                                }, 1500);
                            });
                        }).fail(function () {
                            $("#lock-alert").removeClass("alert-success").addClass("alert-danger").slideDown();
                            $("#lock-alert span").html(arguments[0].responseJSON);
                        });

                    });

                });

                // handle full screen
                $("#fullscreen").click(function () {
                    var dom = document.documentElement;
                    if (dom.requestFullscreen) {
                        dom.requestFullscreen();
                    } else if (dom.mozRequestFullScreen) {
                        dom.mozRequestFullScreen();
                    } else if (dom.webkitRequestFullScreen) {
                        dom.webkitRequestFullScreen();
                    }
                });

                // handle profile
                $("#profile").click(function () {
                    akcy.openwindow("个人资料", 10000, true, "/application/home/profile.html");
                });

                //handle calendar
                $("#calendar").click(function () {
                    akcy.openwindow("我的日程", 10001, true, "/application/home/calendar.html");
                })

                //handle inbox
                $("#inbox").click(function () {
                    akcy.openwindow("系统通知", 'xxlb', true, "/application/System/noticelist.html");
                });

                $("#inbox_all").click(function () {
                    akcy.openwindow("系统通知", 'xxlb', true, "/application/System/noticelist.html");
                });

                //handle todo
                $("#todo").click(function () {
                    akcy.openwindow("我的任务", 10003, true, "/application/home/todo.html");
                })

                $(document).on('click', '.mega-menu-dropdown .dropdown-menu', function (e) {
                    e.stopPropagation();
                });
            };

            // Handles Bootstrap Tabs.
            var handleTabs = function () {
                // fix content height on tab click
                $('body').on('shown.bs.tab', 'a[data-toggle="tab"]', function () {
                    handleSidebarAndContentHeight();
                });
            };

            // Handles the go to top button at the footer
            var handleGoTop = function () {
                var offset = 300;
                var duration = 500;

                if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {  // ios supported
                    $(window).bind("touchend touchcancel touchleave", function (e) {
                        if ($(this).scrollTop() > offset) {
                            $('.scroll-to-top').fadeIn(duration);
                        } else {
                            $('.scroll-to-top').fadeOut(duration);
                        }
                    });
                } else {  // general 
                    $(window).scroll(function () {
                        if ($(this).scrollTop() > offset) {
                            $('.scroll-to-top').fadeIn(duration);
                        } else {
                            $('.scroll-to-top').fadeOut(duration);
                        }
                    });
                }

                $('.scroll-to-top').click(function (e) {
                    e.preventDefault();
                    $('html, body').animate({ scrollTop: 0 }, duration);
                    return false;
                });
            };

            //* END:CORE HANDLERS *//

            return {
                // Main init methods to initialize the layout
                //IMPORTANT!!!: Do not modify the core handlers call order.

                initHeader: function () {
                    handleHorizontalMenu(); // handles horizontal menu    
                },

                setSidebarMenuActiveLink: function (mode, el) {
                    handleSidebarMenuActiveLink(mode, el);
                },

                initSidebar: function () {
                    //layout handlers
                    handleFixedSidebar(); // handles fixed sidebar menu
                    handleSidebarMenu(); // handles main menu
                    handleSidebarToggler(); // handles sidebar hide/show

                    akcy.ui.addResizeHandler(handleFixedSidebar); // reinitialize fixed sidebar on window resize
                },

                initContent: function () {
                    handleTabs(); // handle bootstrah tabs

                    akcy.ui.addResizeHandler(handleSidebarAndContentHeight); // recalculate sidebar & content height on window resize
                },

                initFooter: function () {
                    handleGoTop(); //handles scroll to top functionality in the footer
                },

                init: function () {
                    this.initHeader();
                    this.initSidebar();
                    this.initContent();
                    this.initFooter();
                    //window.setInterval(function () {
                    //    var $iframe = $(".page-content .page:visible").find("iframe");
                    //    try {
                    //        var height = $iframe[0].contentWindow.document.documentElement.scrollHeight;
                    //        $iframe.height(height);
                    //    } catch (ex) { }
                    //}, 200);
                },

                //public function to fix the sidebar and content height accordingly
                fixContentHeight: function () {
                    handleSidebarAndContentHeight();
                },

                initFixedSidebarHoverEffect: function () {
                    handleFixedSidebarHoverEffect();
                },

                initFixedSidebar: function () {
                    handleFixedSidebar();
                },

                getLayoutImgPath: function () {
                    return "/Application/Global/Img/";
                },

                getLayoutCssPath: function () {
                    return "/Application/Global/Css/";
                }
            };

        }();

        var handleQuicksidebar = function () {

            // Handles quick sidebar toggler
            var handleQuickSidebarToggler = function () {
                // quick sidebar toggler
                $('.top-menu .dropdown-quick-sidebar-toggler a, .page-quick-sidebar-toggler').click(function (e) {
                    $('body').toggleClass('page-quick-sidebar-open');
                });
            };

            // Handles quick sidebar chats
            var handleQuickSidebarChat = function () {
                var wrapper = $('.page-quick-sidebar-wrapper');
                var wrapperChat = wrapper.find('.page-quick-sidebar-chat');

                var initChatSlimScroll = function () {
                    var chatUsers = wrapper.find('.page-quick-sidebar-chat-users');
                    var chatUsersHeight;

                    chatUsersHeight = wrapper.height() - wrapper.find('.nav-justified > .nav-tabs').outerHeight();

                    // chat user list 
                    akcy.ui.destroySlimScroll(chatUsers);
                    chatUsers.attr("data-height", chatUsersHeight);
                    akcy.ui.initSlimScroll(chatUsers);

                    var chatMessages = wrapperChat.find('.page-quick-sidebar-chat-user-messages');
                    var chatMessagesHeight = chatUsersHeight - wrapperChat.find('.page-quick-sidebar-chat-user-form').outerHeight() - wrapperChat.find('.page-quick-sidebar-nav').outerHeight();

                    // user chat messages 
                    akcy.ui.destroySlimScroll(chatMessages);
                    chatMessages.attr("data-height", chatMessagesHeight);
                    akcy.ui.initSlimScroll(chatMessages);
                };

                initChatSlimScroll();
                akcy.ui.addResizeHandler(initChatSlimScroll); // reinitialize on window resize

                var chatContainer = wrapperChat.find(".page-quick-sidebar-chat-user-messages");
                var getLastPostPos = function () {
                    var height = 0;
                    chatContainer.find(".post").each(function () {
                        height = height + $(this).outerHeight();
                    });

                    return height;
                };

                var viewModel = {
                    users: ko.observableArray([]),
                    chats: ko.observableArray([]),
                    chatshow: function (data, element) {
                        //clear unread
                        if (viewModel.users()[viewModel.users().indexOf(data)].unread > 0) {
                            akcy.ajaxpostsilent("/ak56api/hubs/ClearChatUnread?sender=" + data.account + "&receiver=" + akcy.currentuser.get());
                            viewModel.users()[viewModel.users().indexOf(data)].unread = 0;
                            var plainJs = ko.toJS(viewModel);
                            viewModel.users(plainJs.users);
                        }
                        //load chat data
                        viewModel.chats([]);
                        viewModel.chats(data.chats);
                        //set receiver
                        viewModel.receiver(data.account);
                        //chat show
                        wrapperChat.addClass("page-quick-sidebar-content-item-shown");
                        chatContainer.slimScroll({
                            scrollTo: getLastPostPos()
                        });
                    },
                    chathide: function () {
                        viewModel.receiver("");
                        wrapperChat.removeClass("page-quick-sidebar-content-item-shown");
                    },
                    receiver: ko.observable(),
                    newChatMessage: ko.observableArray(),
                    chatMessage: function (data, context) {
                        //remove message as the same user
                        viewModel.newChatMessage.remove(function (item) {
                            return item.sender == data.sender;
                        });
                        //set receiver
                        viewModel.receiver(data.sender);
                        //show chat window
                        $('body').addClass('page-quick-sidebar-open');
                        wrapperChat.addClass("page-quick-sidebar-content-item-shown");
                        //load chat data
                        viewModel.users().each(function (item) {
                            if (item.account == data.sender) {
                                //clear unread
                                viewModel.users()[viewModel.users().indexOf(item)].unread = 0;
                                //resfresh render
                                var plainJs = ko.toJS(viewModel);
                                viewModel.users(plainJs.users);
                                //load chat
                                viewModel.chats(item.chats);
                                chatContainer.slimScroll({
                                    scrollTo: getLastPostPos()
                                });
                            }
                        });
                    },
                    newSystemMessage: ko.observableArray(),
                    systemMessage: function (data, context) {
                        //remove message
                        viewModel.newSystemMessage.remove(data);
                        //open winodw
                        var dom = $(context.toElement).closest("li");
                        var pageid = dom.attr("pageid");
                        var pagetitle = dom.attr("pagetitle");
                        var pageurl = dom.attr("pageurl");
                        if (pageid != undefined && pageid != "" &&
                            pagetitle != undefined && pagetitle != "" &&
                            pageurl != undefined && pageurl != "") {
                            akcy.openwindow(pagetitle, pageid, true, pageurl);
                        }
                    }
                };
                ko.applyBindings(viewModel, document.getElementById("quick_sidebar_tab_1"));
                ko.applyBindings(viewModel, document.getElementById("quick_sidebar_tab_1_tab"));
                ko.applyBindings(viewModel, document.getElementById("dropdown-inbox"));
                ko.applyBindings(viewModel, document.getElementById("header_notification_bar"));

                akcy.hub.init({
                    receiveChat: function (message) {
                        viewModel.users().each(function (item) {
                            if (item.account == message.sender) {
                                //if current receiver not message sender
                                if (viewModel.receiver() != message.sender) {
                                    //tip info +1
                                    viewModel.users()[viewModel.users().indexOf(item)].unread += 1;
                                    //add new message
                                    viewModel.newChatMessage.push({ sender: message.sender, senderName: message.senderName, date: message.date, message: message.message, level: message.level });
                                } else {
                                    //set read
                                    akcy.ajaxpostsilent("/ak56api/hubs/ClearChatUnread?sender=" + message.sender + "&receiver=" + akcy.currentuser.get());
                                }
                                //add new chat to render
                                viewModel.chats.push({ senderName: message.senderName, date: message.date, message: message.message, method: 'in' });
                                //add new chat in data
                                viewModel.users()[viewModel.users().indexOf(item)].chats.push({ senderName: message.senderName, date: message.date, message: message.message, method: 'in' });
                                //resfresh render
                                var plainJs = ko.toJS(viewModel);
                                viewModel.users(plainJs.users);
                            }
                        });
                        chatContainer.slimScroll({
                            scrollTo: getLastPostPos()
                        });
                    },
                    receiveMessage: function (message) {
                        //add new message
                        viewModel.newSystemMessage.push({ sender: message.sender, senderName: message.senderName, date: message.date, message: message.title, level: message.level, type: message.type, pageid: message.pageid, pagetitle: message.pagetitle, pageurl: message.pageurl });
                    },
                    initSuccess: function () {
                        akcy.alert.info("通信成功！");

                        akcy.ajaxpostsilent("/ak56api/hubs/GetChatGroupUsers?sessionid=" + akcy.session.get()).done(function (rst) {
                            viewModel.users(rst);
                        });
                    }
                });

                var handleChatMessagePost = function (e) {
                    e.preventDefault();

                    var input = wrapperChat.find('.page-quick-sidebar-chat-user-form .form-control');

                    var text = input.val();
                    if (text.length === 0) {
                        return;
                    }

                    // handle post
                    var time = new Date();
                    viewModel.chats.push({ senderName: $("body").data("currentuser").username, date: time.format("yyyy-MM-dd hh:mm:ss"), message: text, method: 'out' });
                    chatContainer.slimScroll({
                        scrollTo: getLastPostPos()
                    });
                    // push message
                    var lastMessage = chatContainer.find("div.out").last().find("div.message");
                    if (viewModel.receiver() != undefined && viewModel.receiver != "") {
                        akcy.hub.sendChat(viewModel.receiver(), text).fail(function () {
                            lastMessage.css("background-color", "rgb(248, 72, 72)").append("<span class='body' data-bind='text:message'>发送失败！</span>").find("span.arrow").css("border-left-color", "rgb(248, 72, 72)");
                        });
                    } else {
                        lastMessage.css("background-color", "rgb(248, 72, 72)").append("<span class='body' data-bind='text:message'>发送失败！</span>").find("span.arrow").css("border-left-color", "rgb(248, 72, 72)");
                    }


                    input.val("");
                };

                wrapperChat.find('.page-quick-sidebar-chat-user-form .btn').click(handleChatMessagePost);
                wrapperChat.find('.page-quick-sidebar-chat-user-form .form-control').keypress(function (e) {
                    if (e.which == 13) {
                        handleChatMessagePost(e);
                        return false;
                    }
                });
            };

            // Handles quick sidebar tasks
            var handleQuickSidebarAlerts = function () {
                var wrapper = $('.page-quick-sidebar-wrapper');
                var wrapperAlerts = wrapper.find('.page-quick-sidebar-alerts');

                var initAlertsSlimScroll = function () {
                    var alertList = wrapper.find('.page-quick-sidebar-alerts-list');
                    var alertListHeight;

                    alertListHeight = wrapper.height() - wrapper.find('.nav-justified > .nav-tabs').outerHeight();

                    // alerts list 
                    akcy.ui.destroySlimScroll(alertList);
                    alertList.attr("data-height", alertListHeight);
                    akcy.ui.initSlimScroll(alertList);
                };

                initAlertsSlimScroll();
                akcy.ui.addResizeHandler(initAlertsSlimScroll); // reinitialize on window resize
            };

            // Handles quick sidebar settings
            var handleQuickSidebarSettings = function () {
                var wrapper = $('.page-quick-sidebar-wrapper');
                var wrapperAlerts = wrapper.find('.page-quick-sidebar-settings');

                var initSettingsSlimScroll = function () {
                    var settingsList = wrapper.find('.page-quick-sidebar-settings-list');
                    var settingsListHeight;

                    settingsListHeight = wrapper.height() - wrapper.find('.nav-justified > .nav-tabs').outerHeight();

                    // alerts list 
                    akcy.ui.destroySlimScroll(settingsList);
                    settingsList.attr("data-height", settingsListHeight);
                    akcy.ui.initSlimScroll(settingsList);
                };

                initSettingsSlimScroll();
                akcy.ui.addResizeHandler(initSettingsSlimScroll); // reinitialize on window resize
            };

            return {

                init: function () {
                    //layout handlers
                    handleQuickSidebarToggler(); // handles quick sidebar's toggler
                    handleQuickSidebarChat(); // handles quick sidebar's chats
                    handleQuickSidebarAlerts(); // handles quick sidebar's alerts
                    handleQuickSidebarSettings(); // handles quick sidebar's setting
                }
            };

        }();

        var handleVersion = function () {
            akcy.ajaxpostsilent("/ak56api/home/CheckVersion?versionCurrent=" + v).done(function (rst) {
                if (!rst) {
                    window.location = "/";
                }
            }).fail(function () {
                window.location = "/";
            });
        };


        return {

            init: function () {
                //public func


                window.showalert = function (type, msg) {
                    var options = {
                        text: msg,
                        class_name: "gritter-" + type,
                        image: "/global/plugins/gritter/images/" + type + ".png"
                    };
                    switch (type) {
                        case "error":
                            options.title = "错误";
                            break;
                        case "warning":
                            options.title = "警告";
                            break;
                        case "success":
                            options.title = "成功";
                            break;
                        case "msg":
                            options.title = "新消息";
                            break;
                        case "info":
                            options.title = "提醒";
                            break;
                        default:
                            break;

                    }
                    $.gritter.add(options);
                };

                window.showconfirm = function (msg, callback) {
                    var confirm = $('#confirm-modal');
                    confirm.find("p.confirm-msg").html(msg);
                    confirm.find(".confirm-ok").unbind("click").bind("click", function () {
                        callback();
                    });
                    confirm.modal('show');
                };

                window.showloading = function (msg) {
                    akcy.ui.blockUI({
                        target: 'body',
                        boxed: true,
                        message: msg == undefined ? "请等待..." : msg
                    });
                };

                window.hideloading = function () {
                    akcy.ui.unblockUI('body');
                };

                window.openwindow = function (title, pageid, refresh, url) {
                    if (url != "" && url != undefined) {
                        var pagerights = $("body").data("pagerights");
                        var isopen = false;
                        if (pagerights != null && pagerights.length > 0) {
                            for (var i = 0; i < pagerights.length; i++) {
                                if (pagerights[i].P_Url != "" && pagerights[i].P_Url != null && url.toLowerCase().startsWith(pagerights[i].P_Url.toLowerCase())) {
                                    isopen = true;
                                    break;
                                }
                            }
                        }
                        if (!isopen) {
                            akcy.alert.error("您没有进入此页面的权限！");
                            return false;
                        }
                    }
                    //当前版本
                    if (url != undefined && typeof (url) == "string") {
                        var v = window.location.toString().getUrlParm("v");
                        if (url.indexOf("?") > -1) {
                            url = url + "&v=" + v;
                        } else {
                            url = url + "?v=" + v;
                        }
                    }

                    akcy.showloading();
                    var $pageContext = $(".page-content");
                    //var windowHeight = $pageContext.height();
                    var windowHeight = akcy.ui.getViewPort().height -
                    $('.page-header').outerHeight(true) -
                    $('.page-footer').outerHeight(true) -
                    $('.page-title').outerHeight(true) -
                    $('.page-bar').outerHeight(true) - 10;
                    if (pageid == $('#active-page').attr('pageid')) {
                        akcy.hideloading();
                        if (refresh) {
                            $pageContext.find('#' + pageid).find('iframe').attr('src', url);
                        }
                        return;
                    }

                    var newPage = false;
                    var $panel = $pageContext.find('#' + pageid);
                    if ($panel.length == 0) {
                        newPage = true;
                        var $page = $('<div class="page" id="{pageid}"><iframe src="{url}" style="width:100%;height:{height};" frameborder="no" border="0" marginwidth="0" marginheight="0"></iframe></div>'.replace("{pageid}", pageid).replace("{url}", url).replace("{height}", windowHeight + "px"));
                        $pageContext.append($page);
                        $panel = $pageContext.find('#' + pageid);

                        //set ShortCuts data to local for current user
                        setSCs(pageid, title);
                    }
                    else {
                        if (refresh) {
                            $panel.find('iframe').attr('src', url);
                        }
                        else {
                            akcy.hideloading();
                        }
                        $(".mega-menu-content a[pageid=" + pageid + "]").parent().remove();
                    }
                    if ($('#active-page').attr('pageid') != "" && $('#active-page').attr('pageid') != undefined) {
                        $('.mega-menu-content div.row').prepend("<div class='col-md-3'><a href='javascript:;' pageid='{pageid}'>{title}</a></div>".replace("{pageid}", $('#active-page').attr('pageid')).replace("{title}", $('#active-page').html()));
                    }
                    $('#active-page').html(title).attr('pageid', pageid);
                    if (pageid != 'p_dashboard') {
                        if (newPage || (!newPage && refresh)) {
                            $('#active-page').append('<i class="icon-close" title="关闭窗口" onclick="window.closewindow(this,event);"></i>');
                        }
                    }
                    $pageContext.find('div.page').hide();
                    $panel.show();
                    akcy.hideloading();
                };

                window.closewindow = function (elm, event) {
                    var $parnet = $(elm).parent();
                    var avtiveid, pageid;

                    if ($parnet.attr("id") == "active-page") {
                        avtiveid = $parnet.attr("pageid");
                        var $nextPage = $(".mega-menu-content .row div:first-child a");
                        $("#active-page").html($nextPage.html()).attr("pageid", $nextPage.attr("pageid"));
                        $(".page-content").find("#" + $nextPage.attr("pageid")).show();
                        $nextPage.parent().remove();
                    } else {
                        avtiveid = $parnet.attr("pageid");
                        event.stopPropagation();
                        $(elm).closest("div.col-md-3").remove();
                    }
                    $(".page-content").find('#' + avtiveid).remove();
                };

                window.showupload = function (callback, data, exts, isauto, ismulti) {
                    $('#upload-modal-file-upload').uploadify({
                        'buttonClass': 'btn btn-success',
                        'buttonText': '请选择文件',
                        'auto': isauto,
                        'multi': ismulti,
                        'fileTypeExts': exts,
                        'fileSizeLimit': 1024 * 1024 * 10,
                        'formData': data,
                        'swf': '/global/plugins/jquery-uploadify/uploadify.swf',
                        'uploader': '/fileupload', //'/ak56api/service/fileupload'
                        'onUploadStart': function () {
                            $('#upload-modal-status').addClass('success').html('正在上传文件中...').fadeIn();
                            $('#upload-modal .modal-footer .btn').attr('disabled', 'disabled');
                        },
                        'onQueueComplete': function (queueData) {
                            $('#upload-modal .modal-footer .btn').removeAttr('disabled');
                            if (queueData.uploadsErrored != 0) {
                                $('#upload-modal-status').addClass('error').html('文件上传失败').fadeIn();
                            }
                        },
                        'onUploadSuccess': function (file, data, response) {
                            if (response) {
                                data = JSON.parse(data);
                                if (data.state == "success") {
                                    if (typeof callback == 'function') {
                                        callback(data);
                                    }
                                    $('#upload-modal-status').addClass('success').html("上传[" + file.name + "]成功！").fadeIn();

                                    setTimeout(function () {
                                        $('#upload-modal').modal('hide');
                                    }, 1000);
                                }
                                else {
                                    $('#upload-modal-status').addClass('error').html("上传[" + file.name + "]失败！").fadeIn();
                                }
                            }
                        },
                        "onUploadError": function (file, errorCode, errorMsg, errorString) {
                            $('#upload-modal-status').addClass('error').html("上传[" + file.name + "]失败").fadeIn();
                        }
                    });

                    $('#upload-modal-status').html("").hide();
                    $("#upload-modal").modal("show");
                };

                window.currentuser = function () {
                    return $("body").data("currentuser");
                }

                window.download = function (src) {
                    $("#download-iframe").attr("src", src);
                }
                window.openOrder = function (orderNo) {
                    if (orderNo != undefined) {
                        var contracturl = "/application/TransportOrder/transportorder.html?JTONO=" + orderNo;
                        akcy.openwindow("托单查看", 'tdmx', true, contracturl)
                    }


                }
                window.exceptionClick = function (jeId) {
                    if (jeId != undefined) {
                        var contracturl = "/application/Exception/jobexceptiondetail.html?JEID=" + jeId;
                        akcy.openwindow("异常信息", 'bgyc', true, contracturl)
                    }


                }
                window.openContract = function (contractNo) {
                    if (contractNo != undefined) {
                        var contracturl = "/application/stowage/stowagecontractdetail.html?contractNo=" + contractNo;
                        akcy.openwindow("合同明细", 'htmx', true, contracturl);
                    }


                }
                window.handlebranchselect = function () {
                    return window.currentuser().branche != '5';
                }

                window.handlenodeselect = function () {
                    return window.currentuser().node != undefined && window.currentuser().node != '';
                }

                var setSCs = function (pID, pTitle) {
                    if (pID == "p_dashboard") return;
                    if (window.localStorage) {
                        var objSC = {};
                        var curUser = akcy.currentuser.get();
                        if (window.localStorage.getItem("SCS") === null) {
                            //Shortcuts never been set
                            objSC[curUser] = [{ "pI": pID, "pT": pTitle, 'pC': 1, 'pD': new Date() }];
                        }
                        else {
                            var hasSC = false;
                            objSC = JSON.parse(localStorage.getItem("SCS"));
                            if (objSC.hasOwnProperty(curUser)) {
                                for (var idx in objSC[curUser]) {
                                    if (objSC[curUser][idx]["pI"] == pID) {
                                        objSC[curUser][idx]["pC"] = parseInt(objSC[curUser][idx]["pC"]) + 1;
                                        objSC[curUser][idx]["pD"] = new Date();
                                        hasSC = true;
                                    }
                                }
                                if (!hasSC) { objSC[curUser].push({ "pI": pID, "pT": pTitle, 'pC': 1, 'pD': new Date() }); }
                            }
                            else {
                                objSC[curUser] = [{ "pI": pID, "pT": pTitle, 'pC': 1, 'pD': new Date() }];
                            }
                        }
                        objSC[curUser].sort(function (a, b) {
                            if (parseInt(a.pC) == parseInt(b.pC)) {
                                return new Date(b.pD).getTime() - new Date(a.pD).getTime();
                            }
                            else {
                                return parseInt(b.pC) - parseInt(a.pC);
                            }
                        });
                        localStorage.setItem("SCS", JSON.stringify(objSC));
                    }
                }

                //var getSCs = function () {
                //}
                handleVersion();

                handleSession();



                handleTheme();

                handleLayout.init();

                handleQuicksidebar.init();


                //lock background
                $.backstretch([
                     "/Application/Global/Img/bg/1.jpg",
                     "/Application/Global/Img/bg/2.jpg",
                     "/Application/Global/Img/bg/3.jpg",
                     "/Application/Global/Img/bg/4.jpg",
                ], {
                    fade: 1000,
                    duration: 8000
                });

                // handle layout style change
                $('.theme-panel .layout-style-option').change(function () {
                    setThemeStyle($(this).val());
                });

                // set layout style from cookie
                if ($.cookie && $.cookie('layout-style-option') === 'rounded') {
                    setThemeStyle($.cookie('layout-style-option'));
                    $('.theme-panel .layout-style-option').val($.cookie('layout-style-option'));
                }

                $("#demo").click(function () {
                    akcy.openwindow("demo", 11111, true, "/application/demo/demo.html")
                });


                // handle upload file
                $('#upload-modal-upfile-btn').on('click', function () {
                    $('#upload-modal-status').html('').removeClass('error').removeClass('success').hide();
                    $('#upload-modal-file-upload').uploadify('upload', '*');
                });

                //$('#JTONO').on('keypress', function (e) {
                //    if (e.which == 13) {
                //        if ($("#JTONO").val() != null && $("#JTONO").val() != "") {
                //            var a = $("#JTONO").val();
                //            var contracturl = "/application/TransportOrder/transportorder.html?JTONO=" + a;
                //            akcy.openwindow("托单查看", 'tdmx', true, contracturl);
                //        } else {
                //            akcy.alert.warning("请输入运单号！");
                //        }
                //        return false;
                //    }
                //});

            }
        };

    }();
    var table = akcy.table().options({


    }).optionsExtend({

        searchOrder: function () {

            if ($("#JTONO").val() != null && $("#JTONO").val() != "") {
                var a = $("#JTONO").val();
                var contracturl = "/application/TransportOrder/transportorder.html?JTONO=" + a;
                akcy.openwindow("托单查看", 'tdmx', true, contracturl);
                $("#JTONO").val('');
                setTimeout("$('#JTONO').focus()", 1000);
            } else {
                akcy.alert.warning("请输入运单号！");
            }



        }


    }).bind("searchorder");

    $("#JTONO").keypress(function (e) {
        if (e.which == 13) {
            table.getInstance().searchOrder();
        }
    });
    akcy.ui.init();
    main.init();

});

